from flask_jwt import  current_identity
from flask import request
from utils.ext import inner_db, db_transaction, db_add_record
from app.record.model import Record
from utils.request_validate import exception_response
import datetime, json
from common.log.log_config import logger

@exception_response()
@db_transaction(inner_db.session)
def add_record(response):

    if current_identity == None:
        try:
            login_data = json.loads(request.get_data())
            account = login_data['username']
        except :
            logger.info("request don't have username,url is {}".format(request.url))
            account = "Missing data for username field."
    else:
        account = current_identity.email

    ## 分别处理 requese 为 body 或 form 两种形式
    if request.get_data():
        body = request.get_data()
    else:
        body_dict = request.form.to_dict()
        if request.files:                           ##如果 post 是form 表单，则判断是否有附件
            files_dict = request.files.to_dict()
            for (k, v) in files_dict.items():
                body_dict[k] = str(v)
        body = json.dumps(body_dict)

    ## 如果请求 url 是一个下载请求，直接将 response 记作“download request”
    if "/download" in request.path or "LogDownload" in request.path:
        response_data = "download request"
    else:
        response_data = response.data


    record_info = dict(url=request.url, method=request.method, body=body,
                       create_time=datetime.datetime.now(), account=account,
                       status=response.status_code, response=response_data)

    db_add_record(session=inner_db.session,
                  table_schema=Record,
                  filter_info=dict(url='this is non-existent url'),
                  add_info=record_info)
    return response